package sort.seniorSort;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;

import static sort.SortCompare.getArray;

public class Quick {
    public static void sort(Comparable[] a) {
        sort(a, 0, a.length - 1);
    }

    private static void sort(Comparable[] a, int lo, int hi) {
        if (lo >= hi) return;
        int j = partition(a, lo, hi);
        sort(a, lo, j - 1);
        sort(a, j + 1, hi);
    }

    private static int partition(Comparable[] a, int lo, int hi) {
        int i = lo;
        int j = hi+1;
        Comparable v = a[lo];
        while (true) {
            while (less(a[++i], v)) if (i == hi) break;
            while (less(v, a[--j])) if (j == lo) break;
            if (i >= j) break;
            exch(a, i, j);
        }
        exch(a, lo, j);
        return j;
    }

    private static boolean less(Comparable v, Comparable k) {
        return v.compareTo(k) < 0;
    }

    private static void exch(Comparable[] a, int i, int j) {
        Comparable temp = a[i];
        a[i] = a[j];
        a[j] = temp;
    }

    public static boolean isSorted(Comparable[] a){
        for (int i=1; i<a.length;i++){
            if (less(a[i], a[i-1])) return false;
        }
        return true;
    }


    public static void main(String[] args) {
        Comparable[] array = getArray(10);
        System.out.println("原来的数组:" + Arrays.asList(array));
        sort(array);
        System.out.println("排序之后的数组为:" + Arrays.asList(array));
        System.out.println(isSorted(array));
    }
}
